
import Api from '@/api/api-declare';
import PD from '.';
import type { ApiCommonTypes } from '@/api/api-types/api-common-types';
import type { COS_TYPE } from '../enum/pd-enum';
import PdCos from '../class/Cos';

const mapKeys : Array<{uid : string}> = [];
const cosMap = new WeakMap();

//上传文件到cos
type UploadOps = {
	type: COS_TYPE,
	filePath: string,
	originPath?: string,//上传过的文件路径，即第一次上传成功后，cos返回的路径
};

/**
 * 根据桶类型获取cos授权配置
 * @param {COS_TYPE} type 桶类型 
 * @returns 
 */
const getCosAuthConfig = (type: COS_TYPE): Promise<ApiCommonTypes.GetCosAuthRes> => {
	return new Promise((r, j) => {
		Api.ApiCommon.getCosConfig({
			num: 1,//由于cos服务端下发文件有数量上限限制，每次都只申请一个
			type,
		}).then(res => {
			r(res);
		}).catch((err) => {
			PD.UniHelp.modal(`cos鉴权失败：${JSON.stringify(err)}`);
			j();
		});
	});
};


export function upload2cos(ops: UploadOps) : Promise<{cosUrl : string}> {
	return new Promise(async (r, j) => {
		let currentCos : InstanceType<typeof PdCos>;
		if (!ops.originPath) {
			const authConfig = await getCosAuthConfig(ops.type);
			const key = { uid: authConfig.file_list[0] };
			mapKeys.push(key);
			cosMap.set(key, new PdCos(ops.type, authConfig));
			currentCos = cosMap.get(key);
		} else {
			const uid = PD.Tool.getFileNameFromHttpUrl(ops.originPath).split('.')[0];
			const key = mapKeys.find(v => v.uid === uid);
			if (!key) {
				const authConfig = await getCosAuthConfig(ops.type);
				const newkey = { uid: authConfig.file_list[0] };
				mapKeys.push(newkey);
				cosMap.set(newkey, new PdCos(ops.type, authConfig));
				currentCos = cosMap.get(newkey);
			} else {
				currentCos = cosMap.get(key as typeof mapKeys[number]);
			};
		};
		currentCos?.upload(ops.filePath).then(res => {
			r(res);
		}).catch(err => {
			PD.UniHelp.modal(`图片上传失败：${JSON.stringify(err)}`);
			j();
		});
	});
};


